package listbyorder.access001_100.test2;

import listbyorder.utils.ListNode;

/**
 * @author code_yc
 * @version 1.0
 * @date 2021/1/11 19:58
 */
public class Solution2 {
    /*
    思路：递归求解
        首先将当前位置的节点相加
        递归累加后续节点
     */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        return dfs(l1, l2, 0);
    }

    private ListNode dfs(ListNode l, ListNode r, int c) {
        // 如果三者都为空，结果肯定为空
        if (l == null && r == null && c == 0) return null;
        int c1 = 0, c2 = 0;
        if (l != null) {
            c1 = l.val;
            l = l.next;
        }
        if (r != null) {
            c2 = r.val;
            r = r.next;
        }
        int sum = c1 + c2 + c;
        ListNode cur = new ListNode(sum % 10);
        cur.next = dfs(l, r, sum / 10);
        return cur;
    }
}
